// 解析query数据
function queryParse(query: any) {
  let queryText = '';
  for (let key in query) {
    queryText += `${key}=${query[key]}&`;
  }
  return queryText.slice(0, -1);
}

/**
 * Post请求
 * @Method Post
 */
function HttpPost(url: string, param: any) {
  try {
    return new Promise((resolve, reject) => {
      const option = {
        method: 'POST',
        headers: {
          'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: queryParse(param)
      };
      const a = fetch(`${url}`, option);

      a.then((response) => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        try {
          const contentType = response.headers.get('content-type');
          if (contentType && contentType.includes('application/json')) {
            return response.json();
          } else {
            return response.text();
          }
        } catch (er) {
          //todo
        }
        return null;
      })
        .then((data) => {
          resolve(data);
        })
        .catch((error) => {
          reject(null);
        });
    });
  } catch (error) {
    //todo
    throw error;
  }
}

/**
 * Get请求
 * @Method GET
 */
function HttpGet(url: string) {
  try {
    return new Promise((resolve, reject) => {
      const option = {
        method: 'GET',
        headers: {
          'Content-type': 'application/json; charset=UTF-8'
        }
      };
      const a = fetch(`${url}`, option);

      a.then((response) => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
        .then((data) => {
          resolve(data);
        })
        .catch((error) => {
          reject(error);
          throw error;
        });
    });
  } catch (error) {
    //todo
    throw error;
  }
}

export { HttpPost, HttpGet };
